
package com.yjh.admin.controller.chronic;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yjh.admin.dto.chronic.*;
import com.yjh.admin.entity.chronic.PhysicalSigns;
import com.yjh.admin.entity.chronic.Reference;
import com.yjh.admin.server.chronic.EquipmentUserService;
import com.yjh.admin.server.chronic.PhysicalSignsService;
import com.yjh.admin.server.chronic.ReferenceService;
import constant.PhysicalSignsConstants;
import enums.EquipmentTypeEnum;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;
import util.R;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;


/**
 * 体征数据
 *
 * @author GuoBin
 * @date 2020-08-11 17:15:12
 */
@ApiOperation("体征数据")
@RestController
@AllArgsConstructor
@RequestMapping("/physicalsigns")
public class PhysicalSignsController {

    private final PhysicalSignsService physicalSignsService;

    private final EquipmentUserService equipmentUserService;

    private final ReferenceService referenceService;


    /**
     * 分页查询
     * @param page 分页对象
     * @param physicalSigns 体征数据
     * @return
     */
    @ApiOperation("分页查询")
    @GetMapping("/page")
    public R getPhysicalSignsPage(Page page, PhysicalSigns physicalSigns) {
        return  new R<>(physicalSignsService.page(page,Wrappers.query(physicalSigns)));
    }


    /**
     * id查询体征数据
     * @param physicalSignsId id
     * @return R
     */
    @ApiOperation("通过id查询体征数据")
    @GetMapping("/getById")
    public R getById(@RequestParam("physicalSignsId") Integer physicalSignsId){
        return new R<>(physicalSignsService.getById(physicalSignsId));
    }

    /**
     * 新增体征数据
     * @param physicalSignsDto 体征数据
     * @return R
     */
    @ApiOperation("新增体征数据")
    @PostMapping
    public R save(@RequestBody PhysicalSignsDto physicalSignsDto){
        Assert.notNull(physicalSignsDto.getEquipmentId(),"equipmentId不为空！");
        PhysicalSigns physicalSigns = new PhysicalSigns();
        BeanUtil.copyProperties(physicalSignsDto,physicalSigns);
        physicalSigns.setDetails(JSON.toJSONString(physicalSignsDto.getDetails()));

        //查询参考值判断是否异常
        if(Objects.nonNull(physicalSignsDto.getType())&&Objects.nonNull(physicalSignsDto.getDetails())){
            List<Reference> referenceList =  referenceService.queryReferenceByType(physicalSignsDto.getType());
            JSONObject  json =   JSON.parseObject(physicalSigns.getDetails());
            double value = 0;
            String referenceValue = null;
            if(Objects.nonNull(json.getString("value"))){
                value =  Double.parseDouble(json.getString("value"));
                referenceValue =  referenceList.get(0).getReferenceValue();
            }
            switch (physicalSignsDto.getType()){
                case 0://血压
                    int gy =Integer.parseInt(json.getString("SYS"));//高压
                    int dy =Integer.parseInt(json.getString("DIA"));//低压
                    int xl =Integer.parseInt(json.getString("PUL"));//心率
                    for(Reference list: referenceList){
                        if("SYS".equals(list.getCode()) && Integer.parseInt(list.getReferenceValue().split("~")[1])<gy){
                            physicalSigns.setStatus(1);
                        }
                    }
                    break;
                case 1://血糖
                    if(Objects.nonNull(referenceValue)&&value>Double.parseDouble(referenceValue.split("~")[1])){
                        physicalSigns.setStatus(1);
                    }
                    break;
                case 2://胆固醇
                    if(Objects.nonNull(referenceValue)&&value>Double.parseDouble(referenceValue.split("~")[1])){
                        physicalSigns.setStatus(1);
                    }
                    break;
                case 3://尿酸
                    if(Objects.nonNull(referenceValue)&&value>Double.parseDouble(referenceValue.split("~")[1])){
                        physicalSigns.setStatus(1);
                    }
                    break;
                default:
                    break;
            }

        }

        return new R<>(physicalSignsService.save(physicalSigns));
    }





    /**
     * 修改体征数据
     * @param physicalSigns 体征数据
     * @return R
     */
    @ApiOperation("修改体征数据")
    @PutMapping
    public R updateById(@RequestBody PhysicalSigns physicalSigns){
        return new R<>(physicalSignsService.updateById(physicalSigns));
    }

    /**
     * 通过id删除体征数据
     * @param physicalSignsId id
     * @return R
     */
    @ApiOperation("删除体征数据")
    @DeleteMapping("/removeById")
    public R removeById(@RequestParam("physicalSignsId") Integer physicalSignsId){
        return new R<>(physicalSignsService.removeById(physicalSignsId));
    }

    /**
     * 查询全部
     * @param
     * @return R
     */
    @ApiOperation("查询全部")
    @GetMapping("/queryAll")
    public R queryAll(){
        return new R<>(physicalSignsService.list());
    }


    /**
     * 查询
     * @param
     * @return R
     */
    @ApiOperation("按类型查询体征数据")
    @GetMapping("/queryPhysicalSigns")
    public R queryPhysicalSigns(Integer type){
        return new R<>(physicalSignsService.queryPhysicalSigns(type));
    }



    @ApiOperation("查询最新体征")
    @GetMapping("/queryNewPhysicalSigns")
    public R<PhysicalSigns> queryNewPhysicalSigns(Integer custId){
        return new R<>(physicalSignsService.getOne(Wrappers.<PhysicalSigns>query().lambda()
                .eq(PhysicalSigns::getCustId,custId)
                .orderByDesc(PhysicalSigns::getPhysicalSignsId)));
    }



    @ApiOperation("查询已开启设备最新体征")
    @GetMapping("/queryPhysicalSignsByType")
    public R queryPhysicalSignsByType(Integer vipId,Integer custId){
        List<EquipmentPsDto> equipmentPsDtoList = new ArrayList<>();

        //查询已开启监测设备
        List<EquipmentUserDto> equipmentUser = equipmentUserService.queryUserEquipmentList(vipId);
        for(EquipmentUserDto list:equipmentUser){
            EquipmentPsDto equipmentPsDto = new EquipmentPsDto();
            BeanUtil.copyProperties(list,equipmentPsDto);
            equipmentPsDto.setPhysicalSignsType(EquipmentTypeEnum.getValue(equipmentPsDto.getFeaturesName()));
            equipmentPsDtoList.add(equipmentPsDto);
        }

        //查询设备监测的最新数据，没有为空
        for(EquipmentPsDto dto:equipmentPsDtoList){
            //查询最新一条数据
            PhysicalSigns physicalSigns =physicalSignsService.queryPhysicalSignsByOne(dto.getEquipmentId(),custId);
            if(Objects.nonNull(physicalSigns))
                dto.setDetails(JSON.parseObject(physicalSigns.getDetails()));
//			if(Objects.nonNull(physicalSigns)){
//				dto.setPhysicalSignsType(physicalSigns.getType());
//				if(physicalSigns.getDetails().contains("SYS")){//血压
//					dto.setValue(JSON.parseObject(physicalSigns.getDetails()).get("SYS").toString());
//				}else if(physicalSigns.getDetails().contains("value")){
//					dto.setValue(JSON.parseObject(physicalSigns.getDetails()).get("bloodValue").toString());
//				}else{
//					dto.setValue(physicalSigns.getDetails());
//				}
//			}
        }
        return new R<>(equipmentPsDtoList);
    }



    @ApiOperation("查询体征详情")
    @GetMapping("/queryPhysicalSignsDetail")
    public R queryPhysicalSignsDetail(Page page,Integer vipId,Integer type,Integer custId){
        return new R<>(physicalSignsService.page(page,Wrappers.<PhysicalSigns>query().lambda()
                .eq(PhysicalSigns::getVipId,vipId)
                .eq(PhysicalSigns::getCustId,custId)
                .eq(PhysicalSigns::getType,type)));
    }



    @ApiOperation("血压体征统计")
    @GetMapping("/physicalSignsXyStatistics")
    public R<PhysicalSignsStatisticsDto> physicalSignsXyStatistics(Integer type,Integer custId){
        PhysicalSignsStatisticsDto  physicalSignsStatisticsDto = new PhysicalSignsStatisticsDto();
        int abnormalCount =0;
        int normalCount =0;
        //统计上月数据
        List firstList = new ArrayList();
        List secondList = new ArrayList();
        List<PhysicalSigns> physicalSignsList =	physicalSignsService.queryPhysicalSignsStatistics(custId,type);
        for(PhysicalSigns list :physicalSignsList){
            if(PhysicalSignsConstants.NORMALCOUNT_STATUS.equals(list.getStatus())){//正常状态
                normalCount++;
            }
            if(PhysicalSignsConstants.ABNORMALCOUNT_STATUS.equals(list.getStatus())){//异常状态
                abnormalCount++;
            }

            this.parseDetails(list,firstList,secondList,type);
        }
        physicalSignsStatisticsDto.setFirstList(firstList);
        physicalSignsStatisticsDto.setSecondList(secondList);
        physicalSignsStatisticsDto.setAbnormalCount(abnormalCount);
        physicalSignsStatisticsDto.setNormalCount(normalCount);
        physicalSignsStatisticsDto.setMeasuringCount(physicalSignsList.size());
        physicalSignsStatisticsDto.setAbnormalPercentage(physicalSignsList.size()/abnormalCount*100);
        return new R<>(physicalSignsStatisticsDto);
    }




    protected static void  parseDetails(PhysicalSigns  physicalSigns,List firstList,List secondList,Integer type){
        JSONObject  json = JSON.parseObject(physicalSigns.getDetails());
        if(Objects.nonNull(json) && Objects.nonNull(type)) {
            switch (type){
                case 0://血压
                    firstList.add(physicalSigns.getCreateTime()+","+json.get("SYS"));
                    secondList.add(physicalSigns.getCreateTime()+","+json.get("PUL"));
                    break;
                case 1://血糖
                    break;
                case 2://胆固醇
                    break;
                case 3://尿酸
                    break;
                default:
                    break;
            }
        }


    }




    @ApiOperation("预警记录")
    @GetMapping("/queryPhysicalSignsWarning")
    public R queryPhysicalSignsWarning(Page page,Integer vipId,Integer custId){
        return new R<>(physicalSignsService.page(page,Wrappers.<PhysicalSigns>query().lambda()
                .eq(PhysicalSigns::getVipId,vipId)
                .eq(PhysicalSigns::getCustId,custId)
                .ne(PhysicalSigns::getStatus,0)));
    }



    @ApiOperation("处理结果")
    @GetMapping("/addProcessContent")
    public R addProcessContent(@RequestParam(value = "physicalSignsId" ,required=true ) Integer physicalSignsId,
                               @RequestParam(value = "processContent" ,required=true ) String processContent){
        PhysicalSigns  physicalSigns = new PhysicalSigns();
        physicalSigns.setPhysicalSignsId(physicalSignsId);
        physicalSigns.setProcessContent(processContent);
        return new R<>(physicalSignsService.updateById(physicalSigns));
    }


    @ApiOperation("预警管理")
    @GetMapping("/queryWarningRecord")
    public R<IPage<WarningRecordDto>> queryWarningRecord(Page page,
                                                         @RequestParam(required = false, defaultValue = "") String startDate,
                                                         @RequestParam(required = false, defaultValue = "") String endDate,
                                                         @RequestParam(required = false, defaultValue = "") String type,
                                                         @RequestParam(required = false, defaultValue = "") String status,
                                                         @RequestParam(required = false, defaultValue = "") String physicalSignsId){
        List<WarningRecordDto> dto = new ArrayList<>();
        IPage iPage =	physicalSignsService.page(page,Wrappers.<PhysicalSigns>query().lambda()
                .between(!StrUtil.isBlank(startDate),PhysicalSigns::getCreateTime,startDate,endDate)
                .eq(!StrUtil.isBlank(type),PhysicalSigns::getType,type)
                .eq(!StrUtil.isBlank(status),PhysicalSigns::getStatus,status)
                .eq(!StrUtil.isBlank(physicalSignsId),PhysicalSigns::getPhysicalSignsId,physicalSignsId));

        List<PhysicalSigns> physicalSigns =	iPage.getRecords();

        for(PhysicalSigns list:physicalSigns){
            WarningRecordDto warningRecordDto = new WarningRecordDto();
            BeanUtils.copyProperties(list,warningRecordDto);

            CustDto custDto =null;//获取用户信息
            if(Objects.nonNull(custDto)){
                BeanUtils.copyProperties(custDto,warningRecordDto);
            }
            dto.add(warningRecordDto);
        }
        iPage.setRecords(dto);
        return R.<IPage<WarningRecordDto>>builder().data(iPage).build();

    }




}
